package com.jxtc.enterprise.tenant.controller;

import com.alibaba.fastjson.JSONObject;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.tenant.dto.TenantLoginDTO;
import com.jxtc.enterprise.tenant.service.TenantLoginService;
import com.jxtc.enterprise.tenant.vo.TenantLoginSuccessVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/jxtc/enterprise/tenant")
@RequiredArgsConstructor
@Slf4j
public class TenantLoginController {

    private final TenantLoginService tenantLoginService;
    private final RedisTemplate<String, Object> redisTemplate;

    @ApiResponse(responseCode = "200", description = "登录成功时，code 返回 200， data 返回 Admin 相关信息")
    @ApiResponse(responseCode = "200", description = "登录失败时，code 返回 401, message 为错误提示信息，data 为空")
    @Operation(summary = "2.1.1 租户登录接口", tags = {"2.1 租户登录/登出"}, operationId = "2.1.1")
    @PostMapping("/login")
    public Result<TenantLoginSuccessVO> login(@Valid @RequestBody TenantLoginDTO dto) {
        // todo 此处会将登录账号和密码打印出来，后续正式上线时，修改此处的日志打印
        log.info("/tenant/login, request: {}", JSONObject.toJSONString(dto));
        TenantLoginSuccessVO vo = tenantLoginService.loginV2(dto);
        log.info("/tenant/login, response: {}", JSONObject.toJSONString(vo));
        return ResultGenerator.genSuccessResult(vo);
    }

    @ApiResponse(responseCode = "200", description = "登出成功时，code 返回 200， data 为空")
    @ApiResponse(responseCode = "200", description = "登出失败时，code 返回 400, message 为错误提示信息")
    @Parameter(name = "userId", description = "管理员用户 ID", example = "c752804d0cd410267f404dd3f0457a57")
    @Operation(summary = "2.1.2 租户登出接口", tags = {"2.1 租户登录/登出"}, operationId = "2.1.2")
    @GetMapping("/logout")
    public Result<Void> logout(@RequestParam String userId) {
        log.info("/tenant/logout, userId: {}", userId);
        // 退出登录时，将redis中缓存的 userId，token 删除
        redisTemplate.delete(userId);

        return ResultGenerator.genSuccessResult();
    }
}
